package ar.edu.unq.sandsoft.constructors;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import ar.edu.unq.sandsoft.exceptions.CouldnFindAttribute;
import ar.edu.unq.sandsoft.utils.SandFile;

public class SandFileReader extends AbstractSandReader {

    private static final String KEY = "key";

    private static final String TYPE = "type";

    private static final String VAR = "var";

    private static final String CLASS = "class";

    private String keyProperty;

    public SandFileReader(final SandFile file) {
        super(file);
    }

    /**
     * Asumes only one tag named 'class'.
     */
    public String findClassName() {
        return getAssociatedDocument().getElementsByTagName(CLASS).item(0).getAttributes().getNamedItem(NAME)
                .getNodeValue();
    }

    /**
     * @return association between attributes name and type enclosed in a 'var'
     *         tag.
     */
    public Map<String, String> findAttributes() throws CouldnFindAttribute {
        Map<String, String> attributesRelation = new HashMap<String, String>();
        NodeList varTagged = this.getAssociatedDocument().getElementsByTagName(VAR);
        String attributeName;
        String attributeValue;
        for (int i = 0; i < varTagged.getLength(); i++) {
            attributeName = findAttribute(NAME, varTagged.item(i));
            attributeValue = findAttribute(TYPE, varTagged.item(i));
            attributesRelation.put(attributeName, attributeValue);
        }
        return attributesRelation;
    }

    public ClassConstructor createClassConstructor() throws CouldnFindAttribute {
        return new ClassConstructor(this.findAttributes(), this.findClassName());
    }

    public Object instanceClass() throws SecurityException, SAXException, IOException, ParserConfigurationException,
            CouldnFindAttribute, ClassNotFoundException, NoSuchMethodException, InstantiationException,
            IllegalAccessException {
        return createClassConstructor().instance();

    }

    public void lookupKey() {
        setKeyProperty(this.getAssociatedDocument().getElementsByTagName(KEY).item(0).getAttributes()
                .getNamedItem(NAME).getNodeValue());
    }

    public void setKeyProperty(String keyProperty) {
        this.keyProperty = keyProperty;
    }

    public String getKeyProperty() {
        return keyProperty;
    }
}